package com.sophialex.health.record.common.showKtable;

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jxl.Workbook;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;

import com.sophialex.health.record.common.Messages;
import com.sophialex.health.record.common.dialog.MyProgressMonitorDialog;
import com.sophialex.health.system.frame.dialog.DialogManager;
import com.sophialex.health.system.frame.dialog.MessageDialog;
import com.sophialex.health.system.frame.util.Assert;
import com.sophialex.health.system.lktable.LKTable;

import de.kupzog.ktable.KTable;

public class ExportTable {
	private static Exception exception = null;

	// 将KTable导出成Excel文件
	public static void exportToExcel(String sheetname, KTable table)
			throws Exception {
		int colimns = table.getModel().getColumnCount();// 列数
		int rows = table.getModel().getRowCount();// 行数
		int fixhead = table.getModel().getFixedHeaderRowCount() - 1;// 表头
		String[][] strs = new String[rows][colimns];
		String[] str1;
		for (int i = 0; i < rows; i++) {
			str1 = new String[colimns];
			for (int j = 0; j < colimns; j++) {
				str1[j] = table.getModel().getContentAt(j, i).toString();
			}
			strs[i] = str1;
		}

		exportToExcel(sheetname, strs, fixhead, null);
	}

	/**
	 * 网络申请单
	 * 
	 * @param sheetname
	 * @param table
	 * @throws Exception
	 */
	public static void exportToExcelForWlsq(String sheetname, LKTable table)
			throws Exception {
		int colimns = table.getModel().getColumnCount() - 1;// 列数
		int rows = table.getModel().getRowCount() - 1;// 行数
		// int fixhead = table.getModel().getFixedHeaderRowCount() - 1; // 表头
		String[][] strs = new String[rows][colimns];
		String[] str1;
		for (int i = 0; i < rows; i++) {
			str1 = new String[colimns];
			for (int j = 0; j < colimns; j++) {
				str1[j] = table.getModel().getContentAt(j + 1, i + 1)
						.toString();
			}
			strs[i] = str1;
		}

		exportToExcel(sheetname, strs, 1, null);
	}
	/***
	 * 
	 * @param sheetname多表头
	 * @param table
	 * @param digital
	 * @throws Exception
	 */
	public static void exportToExcelDouble(String sheetname, LKTable table,
			int[] digital) throws Exception {
		int colimns = table.getModel().getColumnCount();// 列数
		int rows = table.getModel().getRowCount() - 1;// 行数
//		int fixhead = table.getModel().getFixedHeaderRowCount() - 1;// 表头
		String[][] strs = new String[rows][colimns];
		String[] str1;
		for (int i = 0; i < rows; i++) {
			str1 = new String[colimns];
			for (int j = 0; j < colimns; j++) {
				str1[j] = table.getModel().getContentAt(j + 1, i + 1).toString();
			}
			strs[i] = str1;
		}

		exportToExcel(sheetname, strs, 1, digital);
	}
	public static void exportToExcel(String sheetname, LKTable table)
			throws Exception {
		int colimns = table.getModel().getColumnCount();// 列数
		int rows = table.getModel().getRowCount();// 行数
		int fixhead = table.getModel().getFixedHeaderRowCount() - 1; // 表头
		String[][] strs = new String[rows][colimns];
		String[] str1;
		for (int i = 0; i < rows; i++) {
			str1 = new String[colimns];
			for (int j = 0; j < colimns; j++) {
				str1[j] = table.getModel().getContentAt(j, i).toString();
			}
			strs[i] = str1;
		}

		exportToExcel(sheetname, strs, fixhead, null);
	}

	// 将KTable导出成Excel文件
	public static void exportToExcel(String sheetname, KTable table,
			int[] digital) throws Exception {
		int colimns = table.getModel().getColumnCount();// 列数
		int rows = table.getModel().getRowCount();// 行数
		int fixhead = table.getModel().getFixedHeaderRowCount() - 1;// 表头
		String[][] strs = new String[rows][colimns];
		String[] str1;
		for (int i = 0; i < rows; i++) {
			str1 = new String[colimns];
			for (int j = 0; j < colimns; j++) {
				str1[j] = table.getModel().getContentAt(j, i).toString();
			}
			strs[i] = str1;
		}

		exportToExcel(sheetname, strs, fixhead, digital);
	}
	
	public static void exportToExcel(String sheetname, LKTable table,
			int[] digital) throws Exception {
		int colimns = table.getModel().getColumnCount();// 列数
		int rows = table.getModel().getRowCount();// 行数
		int fixhead = table.getModel().getFixedHeaderRowCount() - 1;// 表头
		String[][] strs = new String[rows][colimns];
		String[] str1;
		for (int i = 0; i < rows; i++) {
			str1 = new String[colimns];
			for (int j = 0; j < colimns; j++) {
				str1[j] = table.getModel().getContentAt(j, i).toString();
			}
			strs[i] = str1;
		}

		exportToExcel(sheetname, strs, fixhead, digital);
	}

	// 将二维数组strs导出成Excel文件 sheetname为Excel的sheet名称
	public static void exportToExcel(String sheetname, String[][] strs,
			int fixRow, int[] digital) throws Exception {
		final String filename = DialogManager.invokeFileDlg(SWT.SAVE, null,
				".xls", new String[] { "*.xls" }); //$NON-NLS-1$ //$NON-NLS-2$
		if (filename == null || "".equals(filename)) { //$NON-NLS-1$
			return;
		}
		FileOutputStream os = null;
		try {
			os = new FileOutputStream(filename);
		} catch (IOException ex) {
			System.out.println(Messages.ExportTable_3 + ex.getMessage());
		}
		WritableWorkbook workbook = null;
		try {
			// 创建新的Excel 工作簿
			workbook = Workbook.createWorkbook(os);
			// 在Excel工作簿中建一工作表，其名为:第一页
			jxl.write.WritableSheet wsheet = workbook.createSheet(sheetname, 0); // sheet();
			WritableFont font = new WritableFont(WritableFont.ARIAL, 14,
					WritableFont.BOLD, false,
					jxl.format.UnderlineStyle.NO_UNDERLINE,
					jxl.format.Colour.BLACK);
			WritableCellFormat format = new WritableCellFormat(font);

			font = new jxl.write.WritableFont(WritableFont.createFont("宋体"), //$NON-NLS-1$
					12, WritableFont.NO_BOLD, false,
					jxl.format.UnderlineStyle.NO_UNDERLINE,
					jxl.format.Colour.BLACK);
			format = new jxl.write.WritableCellFormat(font);
			for (int i = 0; i < strs.length; i++) { // 在索引0的位置创建行（最顶端的行）
				// Object obj = (Object) list.get(i);
				String[] sdata = strs[i];
				for (int j = 0; j < sdata.length; j++) { // 在索引0的位置创建单元格（左上端）
					String str = sdata[j];
					if (str == null || "null".equals(str)) //$NON-NLS-1$
						str = ""; //$NON-NLS-1$
					if (digital != null && i > fixRow) {
						if (isDigital(digital, j)) {
							if (!Assert.isNull(str)) {
								try {
									jxl.write.Number labelN = new jxl.write.Number(
											j, i, new Double(str.replace(",", //$NON-NLS-1$
													"")));// 数字类型 //$NON-NLS-1$
									wsheet.addCell(labelN);
								} catch (Exception e) {
									jxl.write.Label wlabel1 = new jxl.write.Label(
											j, i, str, format); // 行、列、单元格中的文本、文本格式
									wsheet.addCell(wlabel1);
								}
								continue;
							}
						}
					}
					jxl.write.Label wlabel1 = new jxl.write.Label(j, i, str,
							format); // 行、列、单元格中的文本、文本格式
					wsheet.addCell(wlabel1);
				}
			}
			workbook.write(); // 写入文件
		} catch (WriteException ex1) {
			System.out.println("WriteException:" + ex1.getMessage()); //$NON-NLS-1$
		} catch (IOException ex2) {
			System.out.println("IOException:" + ex2.getMessage()); //$NON-NLS-1$
		}
		workbook.close();
		os.close();
	}

	private static boolean isDigital(int[] digital, int j) {
		if (digital != null) {
			for (int i : digital) {
				if (j == i)
					return true;
			}
		}
		return false;
	}

	public static void exportToExcel(final String sheetname, final Table table)
			throws Exception {
		final String filename = DialogManager.invokeFileDlg(SWT.SAVE, null,
				".xls", new String[] { "*.xls" }); //$NON-NLS-1$ //$NON-NLS-2$
		if (filename == null || "".equals(filename)) { //$NON-NLS-1$
			return;
		}
		final String[] titles = new String[table.getColumnCount()];
		for (int i = 0; i < table.getColumnCount(); i++) {
			titles[i] = table.getColumns()[i].getText();
		}
		final Map<Integer, List<String>> hm = new HashMap<Integer, List<String>>();
		TableItem[] tItem = table.getItems();
		List<String> temp = new ArrayList<String>();
		if (tItem != null && tItem.length > 0) {
			for (int i = 0; i < tItem.length; i++) {
				// temp1.add(tItem[i].getText(1));
				temp = new ArrayList<String>();
				for (int j = 0; j < table.getColumnCount(); j++) {
					temp.add(tItem[i].getText(j));
				}
				// hm.put("T2", temp1);
				hm.put(i, temp);
			}
			if (hm != null && hm.size() > 0) {
				try {
					exception = null;
					MyProgressMonitorDialog progressDialog = new MyProgressMonitorDialog(
							Display.getCurrent().getActiveShell());

					IRunnableWithProgress runnable = new IRunnableWithProgress() {
						public void run(IProgressMonitor monitor)
								throws InvocationTargetException,
								InterruptedException {
							// TODO Auto-generated method stub
							monitor.beginTask(Messages.ExportTable_14,
									IProgressMonitor.UNKNOWN);
							try {
								String sheet = sheetname;
								if (sheetname == null && "".equals(sheetname)) { //$NON-NLS-1$
									sheet = "sheet1"; //$NON-NLS-1$
								}

								FileOutputStream os = null;

								os = new FileOutputStream(filename);

								WritableWorkbook workbook = null;
								// 创建新的Excel 工作簿
								workbook = Workbook.createWorkbook(os);
								// 在Excel工作簿中建一工作表，其名为:第一页
								jxl.write.WritableSheet wsheet = workbook
										.createSheet(sheet, 0); // sheet();
								WritableFont font = new WritableFont(
										WritableFont.ARIAL, 14,
										WritableFont.BOLD, false,
										jxl.format.UnderlineStyle.NO_UNDERLINE,
										jxl.format.Colour.BLACK);
								WritableCellFormat format = new WritableCellFormat(
										font);
								for (int i = 0; i < titles.length; i++) {
									jxl.write.Label wlabel1 = new jxl.write.Label(
											i, 0, titles[i], format); // 行、列、单元格中的文本、文本格式
									wsheet.addCell(wlabel1);
								}
								font = new jxl.write.WritableFont(WritableFont
										.createFont("宋体"), 12, //$NON-NLS-1$
										WritableFont.NO_BOLD, false,
										jxl.format.UnderlineStyle.NO_UNDERLINE,
										jxl.format.Colour.BLACK);
								format = new jxl.write.WritableCellFormat(font);
								for (int i = 0; i < hm.size(); i++) { // 在索引0的位置创建行（最顶端的行）
									List<String> contextMx = hm.get(i);
									for (int j = 0; j < contextMx.size(); j++) {
										String str = contextMx.get(j);
										if (str == null || "null".equals(str)) //$NON-NLS-1$
											str = ""; //$NON-NLS-1$
										jxl.write.Label wlabel1 = new jxl.write.Label(
												j, i + 1, str, format); // 行、列、单元格中的文本、文本格式
										wsheet.addCell(wlabel1);
									}
								}
								workbook.write(); // 写入文件
								workbook.close();
								os.close();
							} catch (Exception e) {
								exception = e;
							}
						}
					};
					progressDialog.run(true, false, runnable);
					if (exception != null) {
						MessageDialog.openInformation(null, Messages.ExportTable_20, exception
								.getMessage());
					} else {
						MessageDialog.openInformation(null, Messages.ExportTable_21, Messages.ExportTable_22);
					}
				} catch (Exception e) {
					MessageDialog.openInformation(null, "", e.getMessage()); //$NON-NLS-1$
				}
			}
		}
	}
}
